package com.shengdong.water.code.viewmodel

import androidx.lifecycle.viewModelScope
import com.shengdong.water.base.BaseViewModel
import com.shengdong.water.code.bean.NotifyMsg
import com.shengdong.water.code.bean.PageData
import com.shengdong.water.code.repository.ApiRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class NoticeViewModel @Inject constructor(
    private val repository: ApiRepository
) : BaseViewModel()   {


    private var currentPage = 1

    private val _notifyMsg = MutableStateFlow<List<NotifyMsg>>(emptyList())
    val notifyMsg: StateFlow<List<NotifyMsg>> = _notifyMsg

    private var isRefreshing = false

    fun getNotify(current: Int, size: Int) {
        handlePagingRequest(
            flow = repository.getNotify(current, size),
            showLoading = true,
            loading = "加载中...",
            onSuccess = { it ->
                _notifyMsg.update { oldList ->
                    if (isRefreshing || currentPage == 1) {
                        isRefreshing = false
                        it
                    }else  {
                        oldList + it.filterNot { newItem ->
                            oldList.any { it.id == newItem.id }
                        }
                    }
                }

                        },
            onError = { code, msg ->
                when (code) {
                    401 ->  {}// 处理未授权
                    403 -> {}// 处理禁止访问
                    else -> showError(msg)
                }

            },
            onException = {e ->
                showError("发生错误: ${e.message}")

            },
        )
    }
}